package org.example.controller;

import org.example.entity.Car;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/car")
public class CarController {

    // 后端的方法定义参数 接收远程参数 (前端发过来的参数)
    // 参数名必须与前端的数据名一致
    // 参数类型必须与前端的数据类型兼容
    @GetMapping("/list")
    public List<Car> list (String carName) {
        // carName一定有值吗? 不一定
        if( carName != null && !carName.equals("")) {
            // select xx from xx where car_name=?
            List<Car> newList = new ArrayList<>();
            for (Car car : carList) {
                if (car.getCarName().contains(carName)) {
                    newList.add(car);
                }
            }
            return newList;
        }
        return carList;
    }

    @PostMapping("/save")
    public String save(Car car) {
        System.out.println(carList.size());
        System.out.println(car);
        car.setId(carList.size() + 1);
        carList.add(car);
        return "success";
    }

    public static List<Car> carList = new ArrayList<>();

    // 静态代码块初始化假数据 (类加载时自动执行)
    static {
        carList.add(new Car(1,"奔驰S600","奔驰",14.5,0));
        carList.add(new Car(2,"宝马730","宝马",15.5,0));
        carList.add(new Car(3,"奥迪Q7","奥迪",16.5,1));
        carList.add(new Car(4,"法拉利911","法拉利",17.5,0));
        carList.add(new Car(5,"兰博基尼毒药","兰博基尼",18.5,0));
    }
}
